<!-- 促销活动-创建活动 -->
<template>
  <div>
    <el-dialog
      title="创建活动"
      :visible.sync="dialogFormVisible"
      :before-close="handleClose"
      width="45%"
    >
      <el-form
        :model="formActivity"
        :rules="rulesActivity"
        ref="refActivity"
        size="small"
        style="padding-right: 3%"
      >
        <el-form-item
          label="活动门店"
          prop="stationId"
          clearable
          :label-width="formLabelWidth"
        >
          <el-select
            v-model="formActivity.stationId"
            :clearable="true"
            filterable
            placeholder="请选择活动门店"
            style="width: 100%"
            @change="handleStationChange"
          >
            <el-option
              v-for="item in stationList"
              :key="item.stationId"
              :label="item.stationName"
              :value="item.stationId"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item
          clearable
          label="活动类型"
          :label-width="formLabelWidth"
          prop="marketActivityType"
        >
          <el-select
            :clearable="true"
            filterable
            v-model="formActivity.marketActivityType"
            placeholder="请选择活动类型"
            style="width: 100%"
          >
            <el-option label="打折" value="DC"></el-option>
            <!-- <el-option label="特价" value="SP"></el-option> -->
          </el-select>
        </el-form-item>
        <el-form-item
          label="活动名称"
          :label-width="formLabelWidth"
          prop="marketActivityName"
        >
          <el-input
            v-model="formActivity.marketActivityName"
            maxlength="20"
            :clearable="true"
            placeholder="请输入活动名称"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="活动日期"
          :label-width="formLabelWidth"
          prop="dataActivity"
        >
          <el-date-picker
            style="width: 100%"
            v-model="dataActivity"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="['00:00:00', '23:59:59']"
            value-format="yyyy-MM-dd HH:mm:ss"
            @change="changeDataActivity"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item
          label="参与商品"
          :label-width="formLabelWidth"
          prop="allOrPart"
        >
          <el-radio-group v-model="formActivity.allOrPart" @input="inputRadio">
            <el-radio v-model="formActivity.allOrPart" label="1"
              >全部商品</el-radio
            >
            <el-radio v-model="formActivity.allOrPart" label="0"
              >指定商品</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="discountNum">
          <el-input-number
            v-show="this.formActivity.allOrPart == '1'"
            v-model="formActivity.discountNum"
            :min="0"
            :max="100"
            :precision="2"
            :step="0.1"
            placeholder="请输入"
            class="div-input-number"
            size="small"
          ></el-input-number>
        </el-form-item>

        <el-table
          :data="formActivity.activityCommodityRulesList"
          border
          max-height="333"
          v-show="this.formActivity.allOrPart !== '1'"
        >
          <el-table-column prop="commodityName" label="商品名称" width="100">
          </el-table-column>
          <el-table-column prop="barCode" label="商品条码" width="150">
          </el-table-column>
          <el-table-column prop="categoryName" label="分类"> </el-table-column>
          <el-table-column prop="salePrice" label="售价（元）" width="100">
          </el-table-column>
          <el-table-column prop="discountNum" label="折扣" width="200">
            <template slot-scope="scope">
              <el-form-item
                :prop="'activityCommodityRulesList.' + scope.$index"
                :rules="{
                  required: true,
                  validator: indexDiscountNumPass,
                  message: '请输入折扣',
                }"
              >
                <el-input-number
                  v-model="scope.row.discountNum"
                  :min="0.01"
                  :max="100"
                  :precision="2"
                  :step="0.1"
                  placeholder="请输入"
                  class="table-input-number"
                  size="small"
                ></el-input-number>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="60">
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                @click="deleteGoods(scope.$index)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div v-show="this.formActivity.allOrPart !== '1'" class="div-foot">
        <i class="el-icon-circle-plus-outline" @click="addGoods"></i>
        <span @click="addGoods">添加商品</span>
      </div>

      <div slot="footer" class="div-button">
        <el-button
          size="medium"
          round
          style="margin-right: 50px"
          @click="handleClose"
          >取 消</el-button
        >
        <el-button type="primary" size="medium" round @click="submitForm"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <el-dialog
      title="添加商品"
      :visible.sync="addGoodsVisible"
      :before-close="addGoodsClose"
    >
      <el-form
        ref="refGoods"
        :model="formGoods"
        label-width="80px"
        size="small"
        :inline="true"
      >
        <el-form-item label="商品名称" prop="commodityName">
          <el-input
            :clearable="true"
            v-model="formGoods.commodityName"
            placeholder="请输入商品名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="商品条码" prop="barCode">
          <el-input
            :clearable="true"
            v-model="formGoods.barCode"
            placeholder="请输入商品条码"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" style="margin-left: 20px" @click="getList"
            >搜索</el-button
          >
          <el-button @click="productReset">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table
        :data="commodityList"
        v-loading="loading"
        border
        max-height="333"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column
          property="commodityName"
          label="商品名称"
        ></el-table-column>
        <el-table-column property="barCode" label="商品条码"></el-table-column>
        <el-table-column property="categoryName" label="分类"></el-table-column>
        <el-table-column
          property="salePrice"
          label="售价（元）"
        ></el-table-column>
        <el-table-column property="inventory" label="库存"></el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        :total="total"
        :page.sync="formGoods.pageNum"
        :limit.sync="formGoods.pageSize"
        @pagination="getList"
      />
      <div slot="footer" class="div-button">
        <el-button
          size="medium"
          round
          style="margin-right: 50px"
          @click="addGoodsClose"
          >取 消</el-button
        >
        <el-button type="primary" size="medium" round @click="goodsVerify"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { cloneDeep } from "lodash";
import {
  getCommodityListApi,
  activityAdd,
  activityUpdate,
} from "@/api/nonOil/goods";
import { listEnterpriseStation } from "@/api/nonOil/putlntoStorage";
export default {
  name: "PromotionalActivityAdd",
  props: {
    dialogFormVisible: {
      type: Boolean,
      default: false,
    },
    enterpriseId: {
      type: Number,
      default: null,
    },
    formActivityData: {
      default: () => {},
    },
    condition: {
      type: String,
      default: "",
    },
  },
  data() {
    var dataActivityPass = (rule, value, callback) => {
      if (this.formActivity.beginTime && this.formActivity.endTime) {
        callback();
      } else {
        callback(new Error("请选择活动日期"));
      }
    };

    var discountNumPass = (rule, value, callback) => {
      if (this.formActivity.allOrPart == "1") {
        if (this.formActivity.discountNum > 0) return callback();
        else return callback(new Error("请输入折扣"));
      } else if (this.formActivity.allOrPart == "0") {
        callback();
      } else {
        callback(new Error("请选择参与商品"));
      }
    };

    var allOrPartPass = (rule, value, callback) => {
      if (this.formActivity.allOrPart == "0") {
        if (this.formActivity.activityCommodityRulesList.length == 0)
          return callback(new Error("请添加商品"));
        else return callback();
      } else if (this.formActivity.allOrPart == "1") {
        callback();
      } else {
        callback(new Error("请选择参与商品"));
      }
    };

    return {
      addGoodsVisible: false,

      // 门店，油站
      stationList: [],
      // 活动日期
      dataActivity: null,

      // 添加活动表单数据
      formLabelWidth: "80px",
      formActivity: {
        stationId: null,
        marketActivityType: null,
        marketActivityName: null,
        beginTime: null,
        endTime: null,
        allOrPart: "1",
        discountNum: null,
        activityCommodityRulesList: [],
      },
      // 创建活动参与产品指定商品列表

      // 添加商品
      commodityList: [],
      total: 0,
      loading: false,
      formGoods: {
        pageNum: 1,
        pageSize: 10,
        enterpriseId: null,
        stationId: null,
        commodityName: null,
        barCode: null,
        commodityIdList: [],
      },
      // 添加商品多选列表
      multipleSelection: [],

      // 创建活动表单校验
      rulesActivity: {
        stationId: [
          {
            required: true,
            message: "请选择活动门店",
            trigger: ["change", "blur"],
          },
        ],
        marketActivityType: [
          {
            required: true,
            message: "请选择活动类型",
            trigger: ["change", "blur"],
          },
        ],
        marketActivityName: [
          {
            required: true,
            message: "请输入活动名称",
            trigger: ["change", "blur"],
          },
        ],
        dataActivity: [
          {
            required: true,
            validator: dataActivityPass,
            trigger: ["change", "blur"],
          },
        ],
        allOrPart: [
          {
            required: true,
            validator: allOrPartPass,
            trigger: ["change", "blur"],
          },
        ],
        discountNum: [
          {
            required: true,
            validator: discountNumPass,
            trigger: ["change", "blur"],
          },
        ],
      },

      // 修改商品列表
      activityCommodityRulesList: [],

      // 删除的
      deleteArray: [],
    };
  },

  methods: {
    // 选择油站
    handleStationChange() {
      this.formActivity.activityCommodityRulesList = [];
    },

    // 指定商品列表折扣校验
    indexDiscountNumPass(rule, value, callback) {
      if (this.formActivity.activityCommodityRulesList.length) {
        const index = rule.field.substr(rule.field.length - 1, 1);
        if (
          this.formActivity.activityCommodityRulesList[index].discountNum > 0
        ) {
          callback();
        } else {
          callback(new Error("请输入折扣"));
        }
      }
    },

    // 选择活动日期
    changeDataActivity() {
      if (this.dataActivity) {
        this.formActivity.beginTime = this.dataActivity[0];
        this.formActivity.endTime = this.dataActivity[1];
      } else {
        this.formActivity.beginTime = null;
        this.formActivity.endTime = null;
      }
    },

    // 点击参与商品
    inputRadio() {
      if (this.formActivity.allOrPart == "0") {
        this.formActivity.discountNum = null;
      } else if (this.formActivity.allOrPart == "1") {
        this.formActivity.activityCommodityRulesList = [];
      }
    },

    // 获取门店油站 // 查询油站
    getStationList() {
      listEnterpriseStation({
        enterpriseId: this.enterpriseId,
        status: "1",
      }).then((res) => {
        this.stationList = res;

        if (this.condition === "add") {
          this.formActivity.stationId = this.stationList[0].stationId;
        }
      });
    },

    handleClose() {
      this.deleteArray = [];
      this.$emit("update:dialogFormVisible", false);
    },

    // 点击添加商品
    addGoods() {
      this.addGoodsVisible = true;
      this.getList();
    },

    // 点击删除商品
    deleteGoods(index) {
      this.deleteArray.push(
        this.formActivity.activityCommodityRulesList[index]
      );
      this.formActivity.activityCommodityRulesList.splice(index, 1);
      if (!this.formActivity.activityCommodityRulesList.length)
        return this.$refs.refActivity.validate(() => {});
    },

    // 创建活动点击确认
    submitForm() {
      this.$refs.refActivity.validate((validActivity) => {
        if (validActivity) {
          let formActivity = cloneDeep(this.formActivity);

          if (formActivity.marketActivityId) {
            // 没有变化的数组
            let noArray = [];
            // 新增的 and 修改折扣
            let array = [];
            // 旧数组删除的
            let deleteArray = [];

            // 查找没有变化的
            this.activityCommodityRulesList.forEach((oldItem) => {
              formActivity.activityCommodityRulesList.forEach((newItem) => {
                if (
                  newItem.activityCommodityId === oldItem.activityCommodityId &&
                  newItem.discountNum === oldItem.discountNum
                ) {
                  noArray.push(newItem);
                }
              });
            });

            // 去除没有变化的
            const arrayActivityCommodityId = cloneDeep(noArray).map((item) => {
              return item.activityCommodityId;
            });

            formActivity.activityCommodityRulesList.forEach((newItem) => {
              if (
                !arrayActivityCommodityId.includes(newItem.activityCommodityId)
              ) {
                array.push(newItem);
              }
            });

            this.deleteArray.forEach((deleteItem) => {
              if (deleteItem.activityCommodityId) {
                deleteItem.isDeleted = "1";
                deleteArray.push(deleteItem);
              }
            });

            const list = [...array, ...deleteArray];

            if (list.length) {
              formActivity.activityCommodityRulesList = list;
            }

            activityUpdate(formActivity).then((res) => {
              if (res && res.code === 200) {
                this.deleteArray = [];
                this.$message.success("活动修改成功!");
                this.handleClose();
              } else {
                this.$message.error(res.msg);
              }
            });
          } else {
            activityAdd(formActivity).then((res) => {
              if (res && res.code === 200) {
                this.$message.success("活动新增成功!");
                this.handleClose();
              } else {
                this.$message.error(res.msg);
              }
            });
          }
        }
      });
    },

    // 获取添加商品列表
    getList() {
      this.loading = true;
      const commodityIdList = this.formActivity.activityCommodityRulesList.map(
        (item) => {
          return item.commodityId;
        }
      );
      this.formGoods.commodityIdList = commodityIdList;
      getCommodityListApi({
        ...this.formGoods,
        stationId: this.formActivity.stationId,
        enterpriseId: this.enterpriseId,
      })
        .then((res) => {
          this.total = res.total;
          this.commodityList = res.rows;
          this.loading = false;
        })
        .catch(() => {
          this.total = 0;
          this.commodityList = [];
          this.loading = false;
        });
    },

    // 添加商品重置
    productReset() {
      this.$refs.refGoods.resetFields();
      this.getList();
    },

    // 添加商品多选
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    // 添加商品取消
    // 退出添加商品弹框
    addGoodsClose() {
      this.addGoodsVisible = false;
      this.multipleSelection = [];
      this.deleteArray = [];
      this.dataFormGoods();
    },

    // 添加商品确认
    goodsVerify() {
      this.multipleSelection.forEach((item) => {
        this.formActivity.activityCommodityRulesList.push(item);
      });
      this.formActivity.activityCommodityRulesList =
        this.formActivity.activityCommodityRulesList.map((item) => {
          if (item.discountNum) {
            return {
              ...item,
            };
          } else {
            return {
              ...item,
              discountNum: undefined,
            };
          }
        });
      this.addGoodsVisible = false;
      this.$refs.refActivity.validate(() => {});
      this.addGoodsClose();
    },

    // 添加商品搜索条件重置
    dataFormGoods() {
      this.formGoods = {
        pageNum: 1,
        pageSize: 10,
        stationId: null,
        commodityName: null,
        barCode: null,
      };
    },
  },

  computed: {},

  watch: {
    dialogFormVisible: {
      deep: true, // 深度监听
      handler(newVal, oldVal) {
        if (newVal) {
          this.formActivity = this.formActivityData;
          if (!this.formActivity.activityCommodityRulesList) {
            this.formActivity.activityCommodityRulesList = [];
          }
          this.activityCommodityRulesList = cloneDeep(
            this.formActivity.activityCommodityRulesList
          );
          if (this.formActivity.marketActivityId) {
            this.dataActivity = [
              this.formActivity.beginTime,
              this.formActivity.endTime,
            ];
          } else {
            this.dataActivity = null;
          }
          this.getStationList();
        } else {
          this.addGoodsClose();
          this.formActivity = {
            stationId: null,
            marketActivityType: null,
            marketActivityName: null,
            beginTime: null,
            endTime: null,
            allOrPart: "1",
            activityCommodityRulesList: [],
          };
          this.dataActivity = null;
          this.$refs.refActivity.resetFields();
        }
      },
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-input-number {
  .el-input-number__decrease {
    display: none;
  }

  .el-input-number__increase {
    display: none;
  }
}

.div-button {
  width: 100%;
  text-align: center;
}

.div-input-number {
  position: relative;
  width: 20%;
  margin-left: 80px;
}

.div-input-number::after {
  text-align: center;
  position: absolute;
  content: "%";
  display: block;
  width: 32px;
  height: 32px;
  background-color: #d5d8dd;
  right: -30px;
  top: 0px;
  border-top-right-radius: 3px;
  border-bottom-right-radius: 3px;
}

.table-input-number {
  position: relative;
  width: 75%;
}

.table-input-number::after {
  text-align: center;
  position: absolute;
  content: "%";
  display: block;
  width: 32px;
  height: 32px;
  background-color: #d5d8dd;
  right: -30px;
  top: 0px;
  border-top-right-radius: 3px;
  border-bottom-right-radius: 3px;
}

.div-foot {
  width: 100%;
  height: 50px;
  border: 1px solid #e2e2e2;
  display: flex;
  align-items: center;

  i {
    font-size: 24px;
    margin: 0px 10px;
  }

  span {
    font-size: 16px;
  }
}
</style>
